<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

use Doctrine\Common\Util\Debug;

class MY_Form_validation extends CI_Form_validation {

	function unique($value, $params) {  
		$CI =& get_instance();  
		$CI->form_validation->set_message('unique', 'The %s is already being used.');

		list($entities, $field) = explode(".", $params, 2);

		if($field == 'username'){
			$CI->load->library('generator');
			$value = $CI->generator->generate_username($entities,$value);
		}

		$email = $CI->doctrine->em->getRepository($entities)->findBy(array($field => $value));
		if($email) return false;

		return true;
	}
	
	function unique_update($value, $params){
		$CI =& get_instance();
		$CI->form_validation->set_message('unique_update', 'The %s is already being used.');

		list($entities, $field) = explode(".", $params, 2);

		if($field == 'username'){
			$CI->load->library('generator');
			$value = $CI->generator->generate_username($entities,$value);
		}

		$data = $CI->doctrine->em->getRepository($entities)->findBy(array($field => $value, 'id' => $_POST['id']));
		if($data) return true;

		$data = $CI->doctrine->em->getRepository($entities)->findBy(array($field => $value));
		if($data) return false;

		return true;
		
	}

	function password_match($value, $params){
		$CI =& get_instance();
		$CI->form_validation->set_message('password_match', "The %s doesn't match to your account");
		$akun = models\Current_user::get_user();

		$u = $CI->doctrine->em->getRepository('models\Akun')->findBy(array(
			'username' => $akun->get_username(),
			'password' => models\Akun::encode_password($value),
		));
		if(!$u){
			$u = $CI->doctrine->em->getRepository('models\Akun')->findBy(array(
			'username' => $akun->get_email(),
			'password' => models\Akun::encode_password($value),
			));
		}
		if(!$u) return false;

		return true;
	}

	function unique_kunjungan($value, $params){
		$CI =& get_instance();
		$CI->form_validation->set_message('unique_kunjungan', "%s ini sudah mendapat jadwal kunjungan hari ini");

		$tanggal = $_POST['tanggal'];

		$kunjungan= $CI->doctrine->em->createQuery("
			SELECT k 
			FROM models\Kunjungan k 
			JOIN k.customer c
			WHERE c.id = '$value'
			AND k.tanggal LIKE '$tanggal%'
			")->getResult();

		if(count($kunjungan) > 0) return false;
		return true;

	}

	function id_exists($value, $params){
		$CI =& get_instance();
		$CI->form_validation->set_message('id_exists', "%s tidak ada dalam database");

		$akun= $CI->doctrine->em->createQuery("
			SELECT a 
			FROM models\Akun a 
			WHERE a.username = '$value'
			")->getResult();

		if(count($akun) > 0) return true;

		return false;
	}
}
